﻿using System;
using System.IO;
using System.Text;

namespace Zjh.PackSerializer.Converters.Base
{
    public class StringConverter : PackConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return objectType.Equals(typeof(string));
        }

        public override bool Read(Stream stream, Type objectType, IPackSerializer serializer, out object output)
        {
            var bufferLength = new byte[4];
            stream.Read(bufferLength, 0, bufferLength.Length);
            var length = BitConverter.ToInt32(bufferLength, 0);
            var buffer = new byte[length];
            stream.Read(buffer, 0, buffer.Length);
            output = Encoding.UTF8.GetString(buffer);
            return true;
        }

        public override bool Write(Stream stream, Type objectType, object input, IPackSerializer serializer)
        {
            var buffer = Encoding.UTF8.GetBytes((string)input);
            var bufferLength = BitConverter.GetBytes((int)buffer.Length);
            stream.Write(bufferLength, 0, bufferLength.Length);
            stream.Write(buffer, 0, buffer.Length);
            return true;
        }
    }
}